//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Validation Application Block
//===============================================================================
// Code file original author: Martin Lapierre, http://devinstinct.com
//===============================================================================

using System;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;

namespace EntLibContrib.Validation.Validators
{
	/// <summary>
	/// Describes a <see cref="TypeValidator{T}"/>.
	/// </summary>
	/// <seealso cref="TypeValidator{T}"/>
	[AttributeUsage(AttributeTargets.Property
			| AttributeTargets.Field
			| AttributeTargets.Method
			| AttributeTargets.Parameter,
			AllowMultiple = true,
			Inherited = false)]
	public sealed class TypeValidatorAttribute : ValueValidatorAttribute
	{
		#region Fields
		/// <summary>
		/// The target type to use instead of the one passed by DoCreateValidator.
		/// </summary>
		private Type overrideTargetType;
		#endregion Fields

		#region Fields
		/// <summary>
		/// The target type to use instead of the one passed by DoCreateValidator.
		/// </summary>
		/// <value>The type of the target.</value>
		public Type TargetType
		{
			get { return overrideTargetType; }
		}
		#endregion Fields

		#region Construction
		/// <summary>
		/// <para>Initializes a new instance of the <see cref="TypeValidatorAttribute"/> </para>
		/// </summary>
		/// <param name="targetType">The target type.</param>
		public TypeValidatorAttribute(Type targetType)
		{
			this.overrideTargetType = targetType;
		}
		#endregion Constructors

		#region Protected Methods
		/// <summary>
		/// Creates the <see cref="Validator"/> described by the attribute object providing validator specific
		/// information.
		/// </summary>
		/// <param name="targetType">Not used.</param>
		/// <returns>The created <see cref="Validator"/>.</returns>
		protected override Validator DoCreateValidator(Type targetType)
		{
			Type typeValidator = typeof(TypeValidator<>).MakeGenericType(overrideTargetType);
			return Activator.CreateInstance(typeValidator, GetMessageTemplate(), null, Negated) as Validator;
		}
		#endregion Methods
	}
}
